package br.edu.ufcg.sig.client;

import java.util.List;

import br.edu.ufcg.sig.client.panels.CriminalFormPanel;
import br.edu.ufcg.sig.client.services.DelictServices;
import br.edu.ufcg.sig.client.services.DelictServicesAsync;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.maps.client.MapWidget;
import com.google.gwt.maps.client.Maps;
import com.google.gwt.maps.client.event.MapClickHandler;
import com.google.gwt.maps.client.geom.LatLng;
import com.google.gwt.maps.client.overlay.Marker;
import com.google.gwt.maps.client.overlay.MarkerOptions;
import com.google.gwt.maps.client.overlay.Polygon;
import com.google.gwt.maps.client.overlay.PolygonOptions;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.RootPanel;
import com.gwtext.client.core.EventObject;
import com.gwtext.client.core.NameValuePair;
import com.gwtext.client.core.RegionPosition;
import com.gwtext.client.widgets.Button;
import com.gwtext.client.widgets.MessageBox;
import com.gwtext.client.widgets.MessageBoxConfig;
import com.gwtext.client.widgets.Panel;
import com.gwtext.client.widgets.event.ButtonListenerAdapter;
import com.gwtext.client.widgets.form.DateField;
import com.gwtext.client.widgets.form.Label;
import com.gwtext.client.widgets.layout.AccordionLayout;
import com.gwtext.client.widgets.layout.BorderLayout;
import com.gwtext.client.widgets.layout.BorderLayoutData;

public class Wikicrimes implements EntryPoint {
	
	private static final DelictServicesAsync DELICT_SERVICES = (DelictServicesAsync) GWT.create(DelictServices.class);

	public void onModuleLoad() {
		if (!Maps.isLoaded()) {
			Window.alert("The Maps API is not installed."
					+ "  The <script> tag that loads the Maps API may be missing or your Maps key may be wrong.");
			return;
		}
		if (!Maps.isBrowserCompatible()) {
			Window.alert("The Maps API is not compatible with this browser.");
			return;
		}	
		
		MapWidget myMap = new MapWidget(LatLng.newInstance(-7.22, -35.88), 13);
		myMap.setSize("800px", "500px");
		myMap.setUIToDefault();
		myMap.addMapClickHandler(new MapClickHandler() {
			public void onClick(final MapClickEvent clickEvent) {
				MessageBox.show(new MessageBoxConfig() {

				      {
				        setTitle("Adicionar Crime");
				        setMsg("Você deseja cadastrar um crime?");
				        setIconCls(MessageBox.QUESTION);
				        setButtons(MessageBox.YESNO);
				        setButtons(new NameValuePair[]{
				                  new NameValuePair("yes", "Sim"),
				                  new NameValuePair("no", "Não")
				                });
				        setCallback(new MessageBox.PromptCallback() {
				        	public void execute(String btnID, String text) {
								if(btnID.equals("yes")){
									openForm(clickEvent);							
								}
								  
							}
							
							private void openForm(MapClickEvent event) {						
								com.gwtext.client.widgets.Window window = new com.gwtext.client.widgets.Window();
								CriminalFormPanel cfp = new CriminalFormPanel(window, event);
								window.setTitle("Cadastro de ocorrência de crime");  
								window.setClosable(true);  
								window.setWidth(368);  
								window.setHeight(535);  
								window.setPlain(true);  
								window.setLayout(new BorderLayout());  
								//window.setLayout(new HorizontalLayout(15));
								BorderLayoutData centerData = new BorderLayoutData(RegionPosition.CENTER);  
								centerData.setMargins(3, 0, 3, 3); 
								window.add(cfp, centerData);
								window.setCloseAction(com.gwtext.client.widgets.Window.HIDE);  
								window.show();							
							}
				         
				        });
				      }
				    });				
				
			}
		});		
		myMap.setContinuousZoom(true);
		myMap.setScrollWheelZoomEnabled(true);

		HorizontalPanel horizontalPanel = new HorizontalPanel();		
				
		Panel accordionPanel = createAccordionPanel(myMap);  
		//accordionPanel.setTitle("");  
		accordionPanel.setHeight(500);  
		accordionPanel.setWidth(200);
		
		loadPoints(myMap);
					
		horizontalPanel.add(myMap);
		horizontalPanel.add(accordionPanel);
		RootPanel.get("Wikicrimes_canvas").add(horizontalPanel);
		
	}
	
	
	private void loadPoints(final MapWidget myMap) {
		DELICT_SERVICES.getAllPoints(new AsyncCallback<List<String>>(){

			public void onFailure(Throwable caught) {
				Window.alert("Não foi possível carregar os crimes");
				
			}

			public void onSuccess(List<String> result) {				
				for(String locationLabel : result){
					String[] latlng = locationLabel.split(" ");
					String lat = latlng[0];
					String lng = latlng[1];
					
					LatLng position = LatLng.newInstance(Double.parseDouble(lat.substring(lat.indexOf("(")+1)),
							Double.parseDouble(lng.substring(0, lng.indexOf(")")-1)));
					
					final MarkerOptions options = makeMarkerOptions(locationLabel);		            
					final Marker marker = new Marker(position, options);
					myMap.addOverlay(marker);
				}				
				
			}
			
			 private MarkerOptions makeMarkerOptions(final String locationLabel)
			    {
			        final MarkerOptions options = MarkerOptions.newInstance();       
			        options.setTitle(locationLabel);        
			        options.setClickable(true);
			        //options.setIcon(makeIcon());        
			        return options;
			    }

			
		});
		
	}


	private Panel createAccordionPanel(final MapWidget myMap) {  
		Panel accordionPanel = new Panel();  
		accordionPanel.setLayout(new AccordionLayout(true));  

		DateField fromDate = new DateField("Período:", "data", 190);  
		fromDate.setAllowBlank(false);		
		DateField toDate = new DateField("Período:", "data", 190);  
		toDate.setAllowBlank(false);
		
		Panel filterPanel = new Panel("Pesquisa", "");  
		//filterPanel.setIconCls("settings-icon");
		
		Label labelPeriodoDe =  new Label("Período: ");
		filterPanel.add(labelPeriodoDe);
		filterPanel.add(fromDate);
		Label labelPeriodoA =  new Label("a ");
		filterPanel.add(labelPeriodoA);
		filterPanel.add(toDate);
		
		
		accordionPanel.add(filterPanel);  

		Panel optionPanel = new Panel("Operações", "");  
		//panelTwo.setIconCls("folder-icon");
		Button hotZones =  new Button("Mostrar Zonas Quentes");
		hotZones.addListener(new ButtonListenerAdapter() {  
			public void onClick(Button button, EventObject e) {
				DELICT_SERVICES.getHotZones(new AsyncCallback<List<String>>(){

					public void onFailure(Throwable caught) {
						Window.alert("Nao foi possivel adicionar as zonas quentes");
						caught.printStackTrace();
						
					}

					public void onSuccess(List<String> result) {						
						for(int index = 0; index < result.size();index++){							 
							String listPoints = result.get(index);
							String coordinates = listPoints.substring(listPoints.toString().lastIndexOf("(")+1);
					    	coordinates = coordinates.substring(0, coordinates.indexOf(")"));
					    	String[] polyPoints = coordinates.split(",");
					    	final LatLng[] points = new LatLng[polyPoints.length];
					    	for(int j = 0; j < polyPoints.length; j++){
					    		String[] latlng = polyPoints[j].split(" ");
					    		double lat = Double.parseDouble(latlng[0]);
					    		double lng = Double.parseDouble(latlng[1]);
					    		points[j] = LatLng.newInstance(lat, lng);
					    	}
					    	PolygonOptions pgo = PolygonOptions.newInstance(true);
					    	final Polygon polygon= new Polygon(points, "#0000FF", 2, 1.0, "#0000FF", 0.3, pgo);
			                polygon.setEditingEnabled(true);
							myMap.addOverlay(polygon); 
						}						
						
						
					}
					
				});
			}
		});
		optionPanel.add(hotZones);
		
		accordionPanel.add(optionPanel);  

/*		Panel panelThree = new Panel("Panel 3", "<p>Panel3 content!</p>");  
		panelThree.setIconCls("user-add-icon");  
		accordionPanel.add(panelThree);  */

		return accordionPanel;  
	}  
	
	
}
